<?php
/**
 *  Email sending handler
 */

// Sécurité
if (!defined("_ECRIRE_INC_VERSION")) return;

include_spip('classes/FeedbackFormidable');
include_spip('functions/pdk_common');
include_spip('functions/pdk_template');

function traiter_admin_email_dist($args, $retours){
	$formulaire = $args['formulaire'];
	$options = $args['options'];
	$saisies = unserialize($formulaire['saisies']);
	$traitements = unserialize($formulaire['traitements']);
	$champs = saisies_lister_champs($saisies);
    
    // If recipients field specified we will add selected auteurs to recipients list
    if ($options['recipients']){		
		$recipients = FeedbackFormidable::CreateAuteursEmailsArray(_request($options['recipients']));
	}
    if (!$recipients)
        $recipients = array();
	
    // Add more recipients
	if ($options['recipients_plus']){
		$recipients_plus = explode(',', $options['recipients_plus']);
		$recipients_plus = array_map('trim', $recipients_plus);
		$recipients = array_merge($recipients, $recipients_plus);
		$recipients = array_unique($recipients);
	}
	
    // If we have recipients, we can continue
	if (count($recipients) > 0){
		include_spip('inc/filtres');
		include_spip('inc/texte');
		
        // Loop through all fields and fill array of values
		$valeurs = array();
		foreach ($champs as $champ){
			$valeurs[$champ] = _request($champ);
		}
        
        // Create sender email address
        if ($options['email_field'] && _request($options['email_field'])){
		    $sender_email = _request($options['email_field']);
	    }
        if (!$sender_email && $options['sender_email']) 
            $sender_email = $options['sender_email'];
        if (!$sender_email) $sender_email = $GLOBALS['meta']['email_webmaster'];
        if (!$sender_email) $sender_email = 'no-reply@'.$_SERVER["SERVER_NAME"];
		
        // Building the name of the sender
        if ($options['name_field'] && _request($options['name_field'])){
		    $sender_name = _request($options['name_field']);
	    }
        if (!$sender_name && $options['sender_name']) 
            $sender_name = pdk_replace_template_fields($options['sender_name'], $valeurs);
		if (!$sender_name) $sender_name = supprimer_tags(typo($GLOBALS['meta']['nom_site']));
        
        // Building subject
        $subject = pdk_replace_template_fields($options['subject'], $valeurs);
		if (!$subject) $subject = _T('feedback_formidable:traiter_admin_email_subject');
		$subject = filtrer_entites($subject);
		
		// Select email template
		if (find_in_path('notifications/formulaire_'.$formulaire['identifiant'].'_admin_email.html'))
			$notification = 'notifications/formulaire_'.$formulaire['identifiant'].'_admin_email';
		else
			$notification = 'notifications/formulaire_admin_email';
		
        $text = $options['text'] ? $options['text'] : '';
        if ($text)
            $text = pdk_replace_template_fields($text, $valeurs);
            
        // Files to attach:
        $attach_files_data = array();
        if ($options['attach_files']) {            
            if ($options['files_field'])
                $attach_files_data = $GLOBALS['uploaded_files_data_'.$options['files_field']];
            // Additional files    
            if ($options['files_plus']) {
                $files = explode("\n", $options['files_plus']);
                foreach ($files as $file) {
                    $file = trim($file);
                    if (file_exists($file))
                        $attach_files_data[] = array('full_path'=>$file);
                }
            }    
        }    
        
        include_spip('functions/pdk_url');
        $page_url = $options['add_url_info']?pdk_request_url():'';
        $user_ip = $options['add_ip_info']?$_SERVER["REMOTE_ADDR"]:'';        
		// Generate the mail message 
		$html = recuperer_fond(
			$notification,
            array_merge(
                array(
				    'id_formulaire' => $formulaire['id_formulaire'],
				    'titre' => _T_ou_typo($formulaire['titre']),
                    'subject' => $subject,
				    'traitements' => $traitements,
    				'saisies' => $saisies,
	       			'valeurs' => $valeurs,
                    'options' => $options,
                    'text'=> $text,
                    'page_url'=> $page_url,
                    'user_ip'=> $user_ip,
                    'attach_files_data'=> $attach_files_data,
                ), $_REQUEST)
		);
        
        $send_method = $options['send_method']?$options['send_method']:'PHPMailer';
        $sender = pdk_load_class("Pdk".$send_method."Sender", 'classes/mail/');
        $ok = $sender->Send($recipients, $subject, $html, array('from_name'=>$sender_name,
                    'from_email'=>$sender_email,'attach_files_data'=>$attach_files_data));
		
		if ($ok && strpos($retours['message_ok'], _T('formidable:traiter_email_message_ok')) === FALSE){            
			 $retours['message_ok'] .= "\n<br/>"._T('formidable:traiter_email_message_ok');
		}
		else if (!$ok && strpos($retours['message_erreur'], _T('formidable:traiter_email_message_erreur')) === FALSE) {
			$retours['message_erreur'] .= "\n<br/>"._T('formidable:traiter_email_message_erreur');
		}
	}
	
	return $retours;
}

?>
